﻿using Aker.DevTeam;
using Aker.Order;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Windows.Forms;

namespace Aker
{
    public partial class NewOrder : XtraForm
    {
        public NewOrder()
        {
            InitializeComponent();
        }

        int OrderId = -1;
        public NewOrder(int orderId)
        {
            InitializeComponent();
            OrderId = orderId;
        }


        AkerDB.OrderRow orderRow;
        AkerDB.BusinessCardRow bcRow;

        private void NewOrder_Load(object sender, EventArgs e)
        {
            cmbCountry.Properties.Items.AddRange(getCountryList());
            cmbCountry.SelectedItem = "Turkey";
            cmbCurrency.SelectedItem = Settings.Currency;
            chkShowroom.Checked = AppSession.Showroom;
            txtBrand.Focus();

            if (OrderId > -1)
            {
                orderRow = Data.DB.Order.FindByOrderId(OrderId);
                if (!orderRow.IsBusinessCardIdNull())
                {
                    bcRow = Data.DB.BusinessCard.FindByBusinessCardId(orderRow.BusinessCardId);
                    piScan.EditValue = bcRow.BusinessCard;
                }
                txtBrand.Enabled = false;
                cmbCountry.Enabled = false;
                txtWebSite.Enabled = false;
                txtPhone.Enabled = false;
                lstContacts.Enabled = false;
                txtContact.Enabled = false;
                txtCarrier.Enabled = false;
                txtEmail.Enabled = false;
                txtAddress.Enabled = false;
                btnAddContact.Enabled = false;
                btnRemoveContact.Enabled = false;
                chkIncludePhotos.Enabled = false;
                chkShowroom.Enabled = false;
                cmbCurrency.Enabled = false;
            }
            else
            {
                orderRow = Data.DB.Order.NewOrderRow();
                bcRow = Data.DB.BusinessCard.NewBusinessCardRow();
            }

            this.Text = Language.MainForm.NewOrder;
            lblBrand.Text = Language.Fair.Brand;
            lblWebSite.Text = Language.Fair.WebSite;
            lblContact.Text = Language.Fair.Contact;
            lblCarrier.Text = Language.Fair.Carrier;
            lblAddress.Text = Language.Fair.Address;
            lblCurrency.Text = Language.Fair.Currency;
            lblCountry.Text = Language.Fair.Country;
            lblPhone.Text = Language.Fair.Phone;
            lblEmail.Text = Language.Fair.Email;
            chkShowroom.Text = Language.Fair.IsShowRoom;
            chkIncludePhotos.Text = Language.Fair.IncludePhotos;
            btnAdd.Text = Language.Save;
            piScan.Properties.NullText = Language.Fair.BusinessCard;
        }

        public static List<string> getCountryList()
        {
            List<string> cultureList = new List<string>();
            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
            foreach (CultureInfo culture in cultures)
            {
                if (culture.LCID != 127 && (culture.CultureTypes & CultureTypes.NeutralCultures) != CultureTypes.NeutralCultures)//NEW LINE
                {
                    RegionInfo region = new RegionInfo(culture.LCID);
                    //if (AppSession.Language == "TR")
                    //    if (!(cultureList.Contains(region.NativeName)))
                    //        cultureList.Add(region.NativeName);
                    //else
                    if (!(cultureList.Contains(region.EnglishName)))
                        cultureList.Add(region.EnglishName);

                }
            }
            cultureList.Sort();
            //put the country list in alphabetic order.21.22. 
            return cultureList;
        }

        private void btnAddContact_Click(object sender, EventArgs e)
        {
            if (txtContact.Text.Trim() == "")
            {
                txtContact.Text = txtEmail.Text = "";
                return;
            }

            DataTable dt = Data.DM.ExecuteDataTable("GetCustomerInfo", txtEmail.Text.Trim());
            List<string> customerInfo = new List<string>();
            foreach (DataRow dr in dt.Rows)
                customerInfo.Add(dr["Info"].ToString());

            string pair = String.Join(";", txtContact.Text.Trim(), txtEmail.Text.Trim());

            if (customerInfo.Count > 0)
            {
                string infos = string.Join(";", customerInfo.ToArray());
                pair = string.Join(";", pair, infos);
            }

            if (!lstContacts.Items.Contains(pair))
            {
                lstContacts.Items.Add(pair);
                txtContact.Text = txtEmail.Text = "";
            }
        }

        private void btnAddCard_Click(object sender, EventArgs e)
        {
            using (CameraViewer camera = new CameraViewer())
            {
                if (camera.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    piScan.Image = camera.LatestImage;
                }
            }
        }

        private void pbCard_Click(object sender, EventArgs e)
        {
            if (piScan.Image != null)
                using (ImageViewer iv = new ImageViewer())
                {
                    iv.picture.Image = piScan.Image;
                    iv.ShowDialog();
                }
        }

        public byte[] BusinessCard
        {
            get
            {
                if (piScan.Image == null)
                    return null;
                else
                {
                    MemoryStream ms = new MemoryStream();
                    piScan.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return ms.ToArray();
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (OrderId > 0)
            {
                if (BusinessCard != null)
                {
                    bcRow.BusinessCard = BusinessCard;
                    Data.TAM.BusinessCardTableAdapter.Update(bcRow);
                    if (orderRow.IsBusinessCardIdNull())
                        orderRow.BusinessCardId = bcRow.BusinessCardId;
                }
                else
                {
                    if (!orderRow.IsBusinessCardIdNull())
                    {
                        orderRow.SetBusinessCardIdNull();
                        bcRow.Delete();
                        Data.TAM.BusinessCardTableAdapter.Update(bcRow);
                    }
                }

                Data.TAM.OrderTableAdapter.Update(orderRow);
            }
            else
            {
                if (txtBrand.Text.Trim() != "")
                    orderRow.Brand = txtBrand.Text.Trim();

                List<string> emails = new List<string>();
                List<string> contacts = new List<string>();

                foreach (string pair in lstContacts.Items)
                {
                    string[] vals = pair.Split(";".ToCharArray());
                    contacts.Add(vals[0]);
                    emails.Add(vals[1]);
                }

                if (contacts.Count > 0)
                    orderRow.Contact = string.Join(";", contacts);

                if (emails.Count > 0)
                    orderRow.Email = string.Join(";", emails);

                if (txtAddress.Text.Trim() != "")
                    orderRow.Address = txtAddress.Text.Trim();

                if (txtPhone.Text.Trim() != "")
                    orderRow.Phone = txtPhone.Text.Trim();

                if (txtCarrier.Text.Trim() != "")
                    orderRow.CarrierCustomerInfo = txtCarrier.Text.Trim();

                if (Settings.FairName.Trim() != "")
                    orderRow.Fair = Settings.FairName.Trim();

                if (Settings.Season.Trim() != "")
                    orderRow.Season = Settings.Season.Trim();


                if (txtWebSite.Text.Trim() != "")
                    orderRow.Website = txtWebSite.Text.Trim();

                if (cmbCountry.SelectedItem.ToStringNN().Trim() != "")
                    orderRow.Country = cmbCountry.SelectedItem.ToStringNN().Trim();

                if (cmbCurrency.SelectedItem.ToStringNN().Trim() != "")
                    orderRow.Currency = cmbCurrency.SelectedItem.ToStringNN().Trim();

                orderRow.PriceType = UserSettings.PriceType;


                if (BusinessCard != null)
                {
                    bcRow.BusinessCard = BusinessCard;
                    Data.TAM.BusinessCardTableAdapter.Update(bcRow);
                    orderRow.BusinessCardId = bcRow.BusinessCardId;
                }
                
                orderRow.UserId = AppSession.UserInfo.UserId;

                orderRow.IsOnline = AppSession.IsOnline;
                orderRow.TerminalNo = Settings.TerminalNo;

                orderRow.Cancelled = false;
                orderRow.InsertDate = DateTime.Now;

                orderRow.Showroom = chkShowroom.Checked;
                orderRow.IncludePhoto = chkIncludePhotos.Checked;

                Data.DB.Order.AddOrderRow(orderRow);

                Data.TAM.OrderTableAdapter.Update(Data.DB.Order);

                AppSession.Showroom = chkShowroom.Checked;
            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnRemoveContact_Click(object sender, EventArgs e)
        {
            if (lstContacts.SelectedIndex > -1)
                lstContacts.Items.RemoveAt(lstContacts.SelectedIndex);
        }

        private void btnRemoveCard_Click(object sender, EventArgs e)
        {
            piScan.Image = null;
        }

        private void txtEmail_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter)
            {
                btnAddContact.PerformClick();
            }
        }

        private void btnList_Click(object sender, EventArgs e)
        {
            using (CustomersAndFairVisitors visitors = new CustomersAndFairVisitors(true))
            {
                visitors.StartPosition = FormStartPosition.CenterScreen;

                if (visitors.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    DataRow dr = visitors.SelectedRow;
                    txtBrand.Text = dr["Brand"].ToStringNN();
                    txtContact.Text = dr["Contact"].ToStringNN();
                    txtEmail.Text = dr["Email"].ToStringNN();
                    txtAddress.Text = dr["Address"].ToStringNN();
                    txtPhone.Text = dr["Phone"].ToStringNN();
                    //fair txtf.Text = dr["Brand"].ToStringNN();
                    //season .Text = dr["Brand"].ToStringNN();
                    cmbCountry.SelectedItem = dr["Country"].ToStringNN();
                    txtCarrier.Text = dr["CarrierCustomerInfo"].ToStringNN();
                    piScan.EditValue = dr["BusinessCard"];

                }
            }
        }
    }
}